package com.generic.action;

import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.generic.dao.impl.MemberDao;
import com.generic.ds.HibernateSession;
import com.generic.module.impl.Member;
import com.generic.util.Constant;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;

@Namespace("/")
@InterceptorRef("jsonValidationWorkflowStack")
public class SignIn extends ActionSupport {
	
	private static final long serialVersionUID = -7415901766283800818L;
	private String email = null;
	private String password = null;
	
	public String getEmail() {
		return email;
	}

	public String getPassword() {
		return password;
	}
	
	@RequiredStringValidator(key = "error.required", shortCircuit = true)
	public void setEmail(String email) {
		this.email = email;
	}

	@RequiredStringValidator(key = "error.required", shortCircuit = true)
	public void setPassword(String password) {
		this.password = password;
	}
	
	@SkipValidation
	public String execute() {
		return SUCCESS;
	}
	
	@Action(value="/sign-in-page",results={
			@Result(name="input",location="ajax-error.jsp"),
			@Result(name="success", location="ajax-msg.jsp")})
	public String page() throws Exception {
		return authenticate();
	}
	
	@Action(value="/sign-in-menu",results={
			@Result(name="input", location="sign-in.jsp"),
			@Result(name="success", type="redirectAction",params={"actionName", "profile", "namespace", "/member"})})
	public String menu() throws Exception {		
		return authenticate();
	}
	
	private String authenticate() {
		String status = SUCCESS;
		HibernateSession hs = new HibernateSession();
		try {			
			MemberDao memberDao = new MemberDao(hs);
			Member member = (Member)memberDao.find("email", email);
			if(member != null && password.equals(member.getPassword())) {
				Map<String, Object> session = ActionContext.getContext().getSession();
				session.put(Constant.SESSION_MEMBER, member);
			} else {
				addActionError(getText("error.failed"));
				status = INPUT;
			}
		} catch (Exception e) {
			hs.rollbackTransaction(e);
			addActionError(getText("error.failed"));
			status = INPUT;
		} finally {
			hs.closeSession();
		}
		
		return status;
	}
}